//
//  Evolution.swift
//  GameOfLife
//
//  Created by LLZ on 16/8/1.
//  Copyright © 2016年 ucsmy. All rights reserved.
//

import UIKit

class Evolution: NSObject {
    private var maxNumX = 0
    private var maxNumY = 0
    
    lazy private var timer:NSTimer = {
        return  NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(Evolution.aotoEvolution), userInfo: nil, repeats: true)
        
    }()
    //单例-----------------------------------
    static let defaultEvolution = Evolution()
    private override init() {}//防止外部用init（）或者（）来初始化这个单例
    //--------------------------------------
    
    
    //初始化（随机产生cell）
    func initializeMap(cellNumX:Int, cellNumY:Int, density:Float) {
        let num = cellNumX * cellNumY
        maxNumX = cellNumX
        maxNumY = cellNumY
        
        for i in 0 ..< num  {
            let cell = Cell()
            
            cell.x = i % cellNumX
            cell.y = i / cellNumX
            if Float(arc4random_uniform(10)) > (density * 10) {
                cell.isAlive = false
                cell.cellView.backgroundColor = UIColor.init(red: 170/255.0, green: 170/255.0, blue: 170/255.0, alpha: 1)
            } else {
                cell.isAlive = true
                cell.cellView.backgroundColor = UIColor.orangeColor()
            }
            NSNotificationCenter.defaultCenter().postNotificationName("Evolution_Initialize", object: self, userInfo: ["cell":cell])
        }
    }
    
    func announceLocation()  {
        NSNotificationCenter.defaultCenter().postNotificationName("Evolution_AnnounceLocation", object: self)
        
        NSNotificationCenter.defaultCenter().postNotificationName("Evolution_Update", object: self)
    }
    func run() {
        self.timer.fire()
    }
    func stop() {
        self.timer.invalidate()
    }
    
    @objc private func aotoEvolution() {
        announceLocation()
    }
    
}
